/*
 * @desc:
 * @Author: 钟强
 * @Date: 2021-11-30 16:08:37
 * @LastEditors: 钟强
 * @LastEditTime: 2021-12-22 18:06:28
 */
import { login, getUserInfo } from '@/api/sys'
import md5 from 'md5'
import { setItem, getItem, removeAllItem } from '@/utils/storage'
import { TOKEN } from '@/constant'
import router, { resetRouter } from '../../router'
import { setTimeStamp } from '../../utils/auth'

export default {
  namespaced: true,
  state: () => ({
    token: getItem(TOKEN),
    userInfo: {}
  }),
  mutations: {
    setToken (state, token) {
      state.token = token
      setItem(TOKEN, token)
    },
    setUserInfo (state, userInfo) {
      state.userInfo = { ...userInfo }
    }
  },
  actions: {
    login (context, userInfo) {
      // 登陆
      const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        login({ username, password: md5(password) }).then((data) => {
          this.commit('user/setToken', data.token)
          setTimeStamp()
          resolve()
        }).catch((err) => {
          reject(err)
        })
      })
    },
    async getUserInfo (context) {
      // 获取用户信息
      const res = await getUserInfo()
      this.commit('user/setUserInfo', { ...res, avatar: 'http://images.izqiang.com/avat.jpg' })
      return res
    },
    logout () {
      resetRouter()
      this.commit('user/setToken', '')
      this.commit('user/setUserInfo', {})
      removeAllItem()
      router.push('/login')
    }
  }
}
